﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Classes;
using System.Drawing;
using System.Data;
using VAdvantage.Logging;
using VAdvantage.Utility;
using VAdvantage.Model;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media.Imaging;

namespace VAdvantage.Model
{
    public class MImage : X_AD_Image
    {
        /// <summary>
        ///Get MImage from Cache
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="AD_Image_ID"></param>
        /// <returns></returns>
        public static MImage Get(Ctx ctx, int AD_Image_ID)
        {
            if (AD_Image_ID == 0)
                return new MImage(ctx, AD_Image_ID, null);
            //
            int key = AD_Image_ID;
            MImage retValue = s_cache[key];
            if (retValue != null)
                return retValue;
            retValue = new MImage(ctx, AD_Image_ID, null);
            if (retValue.Get_ID() != 0)
                s_cache[key] = retValue;
            return retValue;
        }

        /**	Cache						*/
        private static CCache<int, MImage> s_cache = new CCache<int, MImage>("AD_Image", 20);

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="AD_Image_ID"></param>
        /// <param name="trxName"></param>
        public MImage(Ctx ctx, int AD_Image_ID, String trxName)
            : base(ctx, AD_Image_ID, trxName)
        {
            if (AD_Image_ID < 1)
                SetName("-");
        }

        /// <summary>
        ///	Load Constructor
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="rs"></param>
        /// <param name="trxName"></param>
        public MImage(Ctx ctx, DataRow rs, String trxName)
            : base(ctx, rs, trxName)
        {
        }	//	MImage


        /** The Image                   */
        private BitmapImage _image = null;
        /** The Icon                   */
        private Icon _icon = null;

        /// <summary>
        ///	Get Image
        /// </summary>
        /// <returns></returns>
        public BitmapImage GetImage()
        {
            if (_image != null)
                return _image;
            //	Via byte array
            byte[] data = GetBinaryData();
            if (data != null && data.Length > 0)
            {
                try
                {
                    //Toolkit tk = Toolkit.getDefaultToolkit();
                    //m_image = tk.createImage(data);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
                    bool loadingImage = true;

                    if (!System.Windows.Deployment.Current.Dispatcher.CheckAccess())
                    {

                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                           {

                        try
                        {
                            _image = new BitmapImage();
                            _image.SetSource(ms);
                        }
                        catch
                        {

                        }
                        loadingImage = false;
                    });

                        while (loadingImage)
                        {
                            System.Threading.Thread.Sleep(5);
                        }
                    }
                    else
                    {
                        _image = new BitmapImage();
                        _image.SetSource(ms);

                    }
                    //_image =  new Image();//  );//{sou  . .FromStream(ms);
                    //_image.Source = source;
                    return _image;
                }
                catch (Exception e)
                {
                    log.Log(Level.WARNING, "(byteArray)", e);
                    return null;
                }
            }
            //	Via URL
            //URL url = getURL();
            string url = GetURL();




            if (url == null)
                return null;
            try
            {
                //    Toolkit tk = Toolkit.getDefaultToolkit();
                bool loadingImage = true;

                if (!System.Windows.Deployment.Current.Dispatcher.CheckAccess())
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        try
                        {
                            _image = Envs.LoadImageSource(url);
                        }
                        catch
                        {

                        }
                        loadingImage = false;
                    });

                    while (loadingImage)
                    {
                        System.Threading.Thread.Sleep(5);
                    }
                }
                else
                {
                    try
                    {
                        _image = Envs.LoadImageSource(url);
                    }
                    catch
                    {

                    }

                }
                //    m_image = tk.getImage(url);

                return _image;
            }
            catch (Exception e)
            {
                log.Log(Level.WARNING, "(URL)", e);
            }
            return null;
        }   //  getImage


        /**
	 * 	Get URL
	 *	@return url or null
	 */
        //private URL getURL()
        //{
        //    String str = getImageURL();
        //    if (str == null || str.length() == 0)
        //        return null;

        //    URL url = null;
        //    try
        //    {
        //        //	Try URL directly
        //        if (str.indexOf("://") != -1)
        //            url = new URL(str);
        //        else	//	Try Resource
        //            url = getClass().getResource(str);
        //        //
        //        if (url == null)
        //            //log.warning("Not found: " + str);
        //    }
        //    catch (Exception e)
        //    {
        //        //log.warning("Not found: " + str + " - " + e.getMessage());
        //    }
        //    return url;
        //}	
        private string GetURL()
        {
            String str = GetImageURL();
            if (str == null || str.Length == 0)
                return null;

            string url = null;
            try
            {
                //	Try URL directly
                //if (str.IndexOf("://") != -1)
                //    url = new URL(str);
                //else	//	Try Resource
                //    url = getClass().getResource(str);
                ////
                //if (url == null)
                //    //log.warning("Not found: " + str);
                url = str.Substring(str.LastIndexOf("/") + 1);
                return url;

            }
            catch (Exception e)
            {
                log.Warning("Not found: " + str + " - " + e.Message);
            }
            return url;
        }


        /**
         * 	Get Icon
         *	@return icon or null
         */
        public Icon GetIcon()
        {
            if (_icon != null)
                return _icon;
            //	Via byte array
            byte[] data = GetBinaryData();
            if (data != null && data.Length > 0)
            {
                try
                {

                    _icon = null;// new  Icon (ImageIcon(data, getName());
                    return _icon;
                }
                catch (Exception e)
                {
                    log.Log(Level.WARNING, "(byteArray)", e);
                    return null;
                }
            }
            ////	Via URL
            //URL url = getURL();
            //if (url == null)
            //    return null;
            //try
            //{
            //    m_icon = new ImageIcon(url, getName());
            //    return m_icon;
            //}
            //catch (Exception e)
            //{
            //    log.log(Level.WARNING, "(URL)", e);
            //}
            return null;
        }   //  getIcon

        /// <summary>
        ///Get URL
        /// </summary>
        /// <returns></returns>
        //private URL getURL()
        //{
        //    String str = getImageURL();
        //    if (str == null || str.length() == 0)
        //        return null;

        //    URL url = null;
        //    try
        //    {
        //        //	Try URL directly
        //        if (str.indexOf("://") != -1)
        //            url = new URL(str);
        //        else	//	Try Resource
        //            url = getClass().getResource(str);
        //        //
        //        if (url == null)
        //            //log.warning("Not found: " + str);
        //    }
        //    catch (Exception e)
        //    {
        //        //log.warning("Not found: " + str + " - " + e.getMessage());
        //    }
        //    return url;
        //}	//	getURL

        /// <summary>
        /// Set Image URL
        /// </summary>
        /// <param name="imageURL"></param>
        public new void SetImageURL(String imageURL)
        {
            _image = null;
            _icon = null;
            base.SetImageURL(imageURL);
        }	//	setImageURL

        /// <summary>
        /// Set Binary Data
        /// </summary>
        /// <param name="binaryData"></param>
        public new void SetBinaryData(byte[] binaryData)
        {
            _image = null;
            _icon = null;
            base.SetBinaryData(binaryData);
        }	//	setBinaryData

        /// <summary>
        /// Get Data 
        /// </summary>
        /// <returns></returns>
        public byte[] GetData()
        {
            byte[] data = base.GetBinaryData();
            if (data != null)
                return data;
            //	From URL
            String str = GetImageURL();
            if (str == null || str.Length == 0)
            {
                log.Config("No Image URL");
                return null;
            }
            //	Get from URL
            //URL url = getURL();
            //if (url == null)
            //{
            //    log.config("No URL");
            //    return null;
            //}
            //try
            //{
            //    URLConnection conn = url.openConnection();
            //    conn.setUseCaches(false);
            //    InputStream is = conn.getInputStream();
            //    byte[] buffer = new byte[1024*8];   //  8kB
            //    ByteArrayOutputStream os = new ByteArrayOutputStream();
            //    int length = -1;
            //    while ((length = is.read(buffer)) != -1)
            //        os.write(buffer, 0, length);
            //    is.close();
            //    data = os.toByteArray();
            //    os.close();

            //}
            //catch (Exception e)
            //{
            //    log.config (e.toString());
            //}
            return data;
        }	//	getData

        /// <summary>
        ///String Representation
        /// </summary>
        /// <returns></returns>
        public override String ToString()
        {
            return "MImage[ID=" + Get_ID() + ",Name=" + GetName() + "]";
        }


        /// <summary>
        ///Before Save
        /// </summary>
        /// <param name="newRecord"></param>
        /// <returns></returns>
        protected override bool BeforeSave(bool newRecord)
        {
            if (GetAD_Org_ID() != 0)
                SetAD_Org_ID(0);
            return true;
        }
    }   //  MImage
}
